﻿using Microsoft.Extensions.Logging;

namespace GMS.NET.Core.Provider.Logger
{
    /// <summary>
    /// 
    /// </summary>
    public class LoggerExtensions : ILogger
    {

        private readonly string? _logFileBasePath;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="logFileBasePath"></param>
        public LoggerExtensions(string? logFileBasePath)
        {
            _logFileBasePath = logFileBasePath;
        }

        private static readonly object _lock = new object();
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TState"></typeparam>
        /// <param name="state"></param>
        /// <returns></returns>
        public IDisposable BeginScope<TState>(TState state)
        {
            return null!;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="logLevel"></param>
        /// <returns></returns>
        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="TState"></typeparam>
        /// <param name="logLevel"></param>
        /// <param name="eventId"></param>
        /// <param name="state"></param>
        /// <param name="exception"></param>
        /// <param name="formatter"></param>
        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            string logMessage = formatter(state, exception);
            string formattedLogEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [{logLevel}] {logMessage}";

            lock (_lock)
            {
                try
                {
                    using (StreamWriter writer = File.AppendText(_logFileBasePath!))
                    {
                        writer.WriteLine(formattedLogEntry);
                    }
                }
                catch (Exception ex)
                {
                    using (StreamWriter writer = File.AppendText(_logFileBasePath!))
                    {
                        writer.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [Error] 写入日志错误 {ex.Message}{Environment.NewLine}");
                    }
                }
            }
        }
    }
}
